<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\model\Activity;
use app\api\model\Player;
use app\common\controller\Api;
use Exception;
use think\Cache;

/**
 * 订单【这里】
 */
class Order extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];


    /**
     * 创建订单
     * @ApiMethod (POST)
     * @param string activity_id 活动id
     * @param string goods_id 商品id
     * @param string player_id 选手id
     * @param string wish 留言
     *
     */
    public function createOrder()
    {
        $params = $this->request->post();
        $uid = $this->auth->id;
        if (Cache::get("create_order:" . $uid, 0) != 0) {
            $this->error("操作过快");
        }
        Cache::set("create_order:" . $uid, 1, 3);
        $model = new \app\api\model\Order();
        $orderInfo = $model->createOrder($uid, $params);
        $pay = \app\api\model\Order::orderPay($uid, $orderInfo, $this->request->domain() . "/api/order/notify/paytype/wechat");
        $this->success('请求成功', $pay);
    }


    /**
     * 支付成功回调
     */
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            $order = \app\api\model\Order::where("status", 0)
                ->where("order_sn", $out_trade_no)->find();
            if (!empty($order)) {
                \app\api\model\Order::where("status", 0)
                    ->where("order_sn", $out_trade_no)->update([
                        'status' => 1,
                        'pay_time' => time()
                    ]);
                Player::where("id", $order['player_id'])->setInc("vote_number", $order['vote_number']);
                Activity::where("id", $order['activity_id'])->setInc('vote_number', $order['vote_number']);
            }
            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }


}